<!-- 前期的工作 -->
<!-- 1.院区按照顺序进行排列，可以点击 -->
<!-- 2.机房获取需要（院区，影像区域，医院编码） -->
<!-- 3.日期控件：以当前或选中的时间为准往后推一个星期 -->
<!-- 4.重点是列的数据怎么渲染呢，如果是以当前时间分上下的话 -->
<!-- 5.各个接口的对应入参如何拼凑成功 -->
<!-- 6.打印如何移送到vue中 ,把html和pdf都考虑上, 优先考虑pdf 的打印能完成-->
<!-- 7.刷卡应该暂时不用考虑,因为可以直接调用联合预约的按钮获得信息,重点就是信息的传递,参数的获取 -->
<template>
  <div class="appoint-reserve" v-loading="loading">
    <el-button-group v-if="patientInfo.length > 0">
      <el-button v-for="(element, index) in areaNameOptions" :class="{active: activeButtonAreaName === element ? 'testTwo' : ''}" :key="index" @click.native="areaNameChange(element)">{{element}}</el-button>
    </el-button-group>
    <div class="reserve-set">
    </div>
    <el-button-group>
      <el-button v-for="(element, index) in checkRoomOptions" :key="index" :class="{active: activeButtonCheckRoom === element ? 'test' : ''}" @click.native="checkRoomChange(element)">{{element}}</el-button>
    </el-button-group>
    <div class="appoint-Date" v-if="patientInfo.length > 0">
      <el-table :data="tableData" border class="computed-table" style="width: 100%">
        <!-- 纵向参数名表头 -->
        <el-table-column
          v-for="(time, index) in times"
          :key="index"
          :render-header="renderHeader"
          :label="time"
          align="center"
        >
          <template slot-scope="scope">
            {{scope.row}}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { getListByAreaNameFunc } from '@/api/common'
import { getCheckRoomList, getDefaultAppointmentList, getDateAppointmentList } from '@/api/api.js'
import { getDateYMD } from '@/utils/utils'
export default {
  props: {
    hospitalCode: {
      type: String,
      default: ''
    },
    patientInfo: {
      type: Array,
      default: []
    },
    patientCondition: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      loading: false,
      areaNameOptions: [],
      checkRoomOptions: [],
      patientSource: ['门诊', '住院', '体检', '急诊', '外院'],
      formData: {
        dep: '',
        depArea: '学院路院区',
        checkRoom: '磁共振1室',
        appointmentDateBegin: getDateYMD(new Date().getTime())
      },
      everyPrice: 0,
      paramForNumber: {},
      tableNumberData: [],
      tableData: [],
      parameters: Array.from({ length: 15 }, (_, i) => `Parameter${i + 1}`), // 参数名列表
      days: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      times: [],
      activeButtonAreaName: '',
      activeButtonCheckRoom: ''
    }
  },
  watch: {
    patientInfo(val) {
      this.loading = false
      if (val.length > 0 && val[0]) {
        console.error('===patientInfo===', val)
        this.loading = true
        this.formData.dep = val[0].dep || ''
        this.getCheckRoom()
        this.prepareParam()
      }
    }
  },
  created() {
    this.getAreaNameList()
  },
  mounted() {
    // this.times = this.generateTimeLabels()
    this.tableData = this.generateTableData()
  },
  methods: {
    // 获取院区列表
    getAreaNameList() {
      const params = {
        HospitalCode: this.hospitalCode
      }
      getListByAreaNameFunc(params).then(res => {
        this.areaNameOptions = res
      })
      this.loading = false
    },
    // 如果院区改变，默认的号源也将发生改变：(这里需要兼容缓存院区)
    areaNameChange(val) {
      this.activeButtonAreaName = val
    },
    checkRoomChange(val) {
      this.activeButtonCheckRoom = val
    },
    // 获得机房列表
    getCheckRoom() {
      let data = {
        HospitalCode: this.hospitalCode,
        Dep: this.formData.dep
      }
      return new Promise((resolve, reject) => {
        getCheckRoomList(data).then(res => {
          if (res && res.code === 10000) {
            this.loading = false
            this.checkRoomOptions = res.content.list
            resolve()
          }
        })
      })
    },
    // 获得默认号源
    getDefaultAppointmentList() {
      let data = {
        HospitalCode: this.hospitalCode,
        appointmentLogs: this.patientInfo,
        isCheckRoomNum: true,
        appointmentDateBegin: this.formData.appointmentDateBegin,
        areaName: '',
        depArea: '',
        hasAppointmentExamNos: []
      }
      return new Promise((resolve, reject) => {
        getDefaultAppointmentList(data).then(res => {
          if (res && res.code === 10000) {
            this.loading = false
            console.error('res', res)
            resolve()
          }
        })
      })
    },
    renderHeader(h, { column }) {
      return h('span', {}, [
        h('span', {}, column.label.split('/')[0]),
        h('br'),
        h('span', { style: 'color: deepskyblue;' }, column.label.split('/')[1])
      ])
    },
    // 单个申请单获得默认号源
    getDateAppointmentList() {
      this.times = []
      let listParam = JSON.parse(JSON.stringify(this.patientInfo[0]))
      listParam.hospitalCode = this.hospitalCode
      listParam.appointmentDateBegin = this.formData.appointmentDateBegin
      listParam.isAutoDate = true
      return new Promise((resolve, reject) => {
        getDateAppointmentList(listParam).then(res => {
          if (res && res.code === 10000) {
            this.loading = false
            // console.error('res', res)
            let dateLists = res.content.list
            this.getTableTime(dateLists)
            resolve()
          }
        })
      })
    },
    // 处理参数
    prepareParam() {
      this.patientInfo.forEach(patientItem => {
        patientItem.emergency = patientItem.emergency.toString()
        patientItem.examNo = patientItem.applyCode
        patientItem.patAge = patientItem.patientAge
        patientItem.patSex = patientItem.genderTxt
        patientItem.patName = patientItem.patientName
        patientItem.patType = this.patientSource[patientItem.patientSource + 1]
        patientItem.modalityType = patientItem.examClass
        patientItem.applyHospitalCode = this.patientCondition.hospitalCode
        patientItem.appointmentType = this.patientCondition.appointmentType
        patientItem.patBirthday = patientItem.patient.birthDate
        patientItem.examList = this.getExamList(patientItem.examItems, patientItem.applyCode)
        patientItem.price = this.everyPrice
        delete patientItem.patientAge
        delete patientItem.genderTxt
        delete patientItem.examItems
        delete patientItem.patientName
        delete patientItem.patientSource
        delete patientItem.examClass
      })
      // this.getDefaultAppointmentList()
      this.getDateAppointmentList()
    },
    // 处理部位参数
    getExamList(examItems, examNo) {
      this.everyPrice = 0
      let examLists = []
      let examList = {}
      let examPart = []
      let examPartCode = []
      examItems.forEach(examItem => {
        examList = {}
        examItem.examParts.forEach(element => {
          examPart.push(element.examPart)
          examPartCode.push(element.examPartCode)
        })
        examList.amount = examItem.amount
        examList.checkpos = examItem.examItemName
        examList.checkposCode = examItem.examItemCode
        examList.dengjipart = examPart.join(',') || ''
        examList.dengjipartCode = examPartCode.join(',') || ''
        examList.examNo = examItem.examNo || ''
        examList.feeStatus = examItem.feeStatus
        examList.itemNo = examItem.examItemNo || ''
        examList.itemNumber = examItem.amount
        examList.itemPrice = examItem.price
        this.everyPrice = this.everyPrice + examItem.price
        examList.referenceName = examItem.referenceName || ''
        examList.referenceCode = examItem.referenceCode || ''
        examLists.push(examList)
      })
      return examLists
    },
    getTableTime(dateLists) {
      let timeDay = {}
      dateLists.forEach((dateItem, index) => {
        let today = new Date(dateItem.appointmentDate)
        let week = this.days[today.getDay()]
        let timeContent = dateItem.appointmentDate + '/' + week
        this.times.push(timeContent)
        timeDay[timeContent] = {}
        dateItem.depAreaAppointments.forEach((appointment, index2) => {
        // 先把对应的院区和影像区域的内容挑出来,挑出来了之后需要找到可以作为行的标志
          if (appointment.depArea === this.formData.depArea) {
            appointment.checkRoomAppointments.forEach((checkRoomAppo, index3) => {
              if (checkRoomAppo.checkRoom === this.formData.checkRoom) {
              // let locData = []
              // let timesArray = JSON.parse(JSON.stringify(this.times))
                checkRoomAppo.canAppointmentLists.forEach((canAppointmentList, index4) => {
                  this.tableNumberData.push(timeDay)
                  this.tableNumberData[index]
                  // console.error('this.times', this.times, canAppointmentList.appointmentBeginTime.split(' ')[0])
                  // 如果是没有this.times里的时间就需要加一个对应的来填补空白
                  // this.times.forEach(element => {
                  // })
                })
                // this.tableNumberData.push(checkRoomAppo.canAppointmentLists)
                // console.error('timesArray', timesArray)
                console.error('this.tableNumberData', this.tableNumberData)
              }
            })
          }
        })
      })
      // console.error('this.tableNumberData', this.tableNumberData)
    },
    generateTableData() {
      const tableData = this.parameters.map(parameter => ({
        parameter: parameter,
        values: this.generateParameterValues()
      }))
      // console.error('tableData', tableData)
      return tableData
    },
    generateParameterValues() {
      return Array.from({ length: 8 }, (_, i) =>
        Math.floor(Math.random() * 100)
      ) // 48个时间段，每30分钟一个
    }
  }
}
</script>
<style lang="scss" scoped>
.appoint-reserve {
  background-color: #F2F6FC;
}
.reserve-set {
  height: 1%;
  margin-top:5px;
  background-color: white;
}
.computed-table .cell {
  white-space: pre-wrap; /* 保留空白符，自动换行 */
  word-break: break-all; /* 单词换行 */
}
.testTwo{
  color: aqua;
}
.test{
  color:blueviolet;
}
</style>
